<!-- 训练试卷列表 -->
<template>
  <div class="app-container">
    <!-- 搜索工具栏 -->
    <div class="toolbar">
      <el-form :inline="true" :model="queryParams" class="search-form">
        <el-form-item label="状态">
          <el-select
            v-model="queryParams.status"
            placeholder="试卷状态"
            clearable
          >
            <el-option label="未完成" :value="0" />
            <el-option label="已完成" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="来源">
          <el-select
            v-model="queryParams.sourceType"
            placeholder="来源类型"
            clearable
          >
            <el-option label="错题训练" value="WRONG_QUESTIONS" />
            <el-option label="随机训练" value="RANDOM" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <div class="toolbar-buttons">
        <el-button type="success" @click="handleGenerateWrong">
          <el-icon><Document /></el-icon>
          错题训练
        </el-button>
        <el-button type="primary" @click="handleGenerateRandom">
          <el-icon><Document /></el-icon>
          随机训练
        </el-button>
      </div>
    </div>

    <!-- 训练试卷列表 -->
    <el-table v-loading="loading" :data="paperList" style="width: 100%">
      <el-table-column
        prop="paperName"
        label="试卷名称"
        show-overflow-tooltip
      />
      <el-table-column prop="totalScore" label="总分" width="80" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 0 ? 'warning' : 'success'">
            {{ row.status === 0 ? "未完成" : "已完成" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="sourceType" label="来源" width="120">
        <template #default="{ row }">
          <el-tag
            :type="row.sourceType === 'WRONG_QUESTIONS' ? 'danger' : 'primary'"
          >
            {{ row.sourceType === "WRONG_QUESTIONS" ? "错题训练" : "随机训练" }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="createdTime" label="创建时间" width="180" /> -->
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            v-if="row.status === 0"
            type="primary"
            link
            @click="handleContinue(row)"
          >
            继续答题
          </el-button>
          <el-button v-else type="success" link @click="handleViewDetail(row)">
            查看详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 生成错题训练对话框 -->
    <el-dialog v-model="wrongDialogVisible" title="生成错题训练" width="500px">
      <el-form
        ref="wrongFormRef"
        :model="wrongForm"
        :rules="wrongRules"
        label-width="100px"
      >
        <el-form-item label="试卷名称" prop="paperName">
          <el-input
            v-model="wrongForm.paperName"
            placeholder="请输入试卷名称"
          />
        </el-form-item>
        <el-form-item label="题目数量" prop="questionCount">
          <el-input-number
            v-model="wrongForm.questionCount"
            :min="1"
            :max="100"
            controls-position="right"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="wrongDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitWrongForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 生成随机训练对话框 -->
    <el-dialog v-model="randomDialogVisible" title="生成随机训练" width="500px">
      <el-form
        ref="randomFormRef"
        :model="randomForm"
        :rules="randomRules"
        label-width="100px"
      >
        <el-form-item label="科目" prop="subject">
          <el-input v-model="randomForm.subject" placeholder="请输入科目" />
        </el-form-item>
        <el-form-item label="题目数量" prop="questionCount">
          <el-input-number
            v-model="randomForm.questionCount"
            :min="1"
            :max="100"
            controls-position="right"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="randomDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRandomForm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import {
  getTrainingPapers,
  generateFromWrongQuestions,
  generateRandomPaper,
} from "@/api/training";

const router = useRouter();

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  status: "",
  sourceType: "",
});

// 列表数据
const loading = ref(false);
const paperList = ref([]);
const total = ref(0);

// 获取试卷列表
const getList = async () => {
  loading.value = true;
  try {
    const { records, total: totalCount } = await getTrainingPapers(queryParams);
    paperList.value = records;
    total.value = totalCount;
  } catch (error) {
    console.error("获取训练试卷列表失败：", error);
  } finally {
    loading.value = false;
  }
};

// 查询按钮点击
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置按钮点击
const resetQuery = () => {
  queryParams.status = "";
  queryParams.sourceType = "";
  handleQuery();
};

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.pageSize = val;
  getList();
};

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.pageNum = val;
  getList();
};

// 错题训练相关
const wrongDialogVisible = ref(false);
const wrongFormRef = ref(null);
const wrongForm = reactive({
  questionCount: 10,
  paperName: "",
});
const wrongRules = {
  questionCount: [
    { required: true, message: "请输入题目数量", trigger: "blur" },
  ],
  paperName: [{ required: true, message: "请输入试卷名称", trigger: "blur" }],
};

// 生成错题训练按钮点击
const handleGenerateWrong = () => {
  wrongForm.questionCount = 10;
  wrongForm.paperName = "";
  wrongDialogVisible.value = true;
};

// 提交错题训练表单
const submitWrongForm = async () => {
  if (!wrongFormRef.value) return;
  await wrongFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const paper = await generateFromWrongQuestions({
          questionCount: wrongForm.questionCount,
          paperName: wrongForm.paperName,
        });
        ElMessage.success("生成成功");
        wrongDialogVisible.value = false;
        router.push(`/training/paper/${paper.id}`);
      } catch (error) {
        console.error("生成错题训练失败：", error);
      }
    }
  });
};

// 随机训练相关
const randomDialogVisible = ref(false);
const randomFormRef = ref(null);
const randomForm = reactive({
  subject: "",
  questionCount: 10,
});
const randomRules = {
  subject: [{ required: true, message: "请输入科目", trigger: "blur" }],
  questionCount: [
    { required: true, message: "请输入题目数量", trigger: "blur" },
  ],
};

// 生成随机训练按钮点击
const handleGenerateRandom = () => {
  randomForm.subject = "";
  randomForm.questionCount = 10;
  randomDialogVisible.value = true;
};

// 提交随机训练表单
const submitRandomForm = async () => {
  if (!randomFormRef.value) return;
  await randomFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const paper = await generateRandomPaper(
          randomForm.subject,
          randomForm.questionCount
        );
        ElMessage.success("生成成功");
        randomDialogVisible.value = false;
        router.push(`/training/paper/${paper.id}`);
      } catch (error) {
        console.error("生成随机训练失败：", error);
      }
    }
  });
};

// 继续答题
const handleContinue = (row) => {
  router.push(`/training/paper/${row.id}`);
};

// 查看详情
const handleViewDetail = (row) => {
  router.push(`/training/detail/${row.id}`);
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-form {
  flex: 1;
}

.toolbar-buttons {
  display: flex;
  gap: 10px;
  align-items: flex-start;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
